import { View, Text, Input, Button, Textarea, Image } from '@tarojs/components'
import Taro, { useLoad } from '@tarojs/taro'
import { useRef, useState } from 'react'
import axios from '@/request/index'
import classNames from 'classnames'
import './index.scss'

export default function Index() {

  const [visible, setVisible] = useState(false)
  const [inputValue, setInput] = useState('')
  const infoRef = useRef<any>();
  const [messages, setMessages] = useState<any[]>([])
  const testList = ['氯吡格雷副作用有哪些？', '氯吡格雷饭前吃还是饭后吃？', '如何正确使用氯吡格雷？', '氯吡格雷能治疗什么病？']
  useLoad(() => {
    console.log('Page loaded.')
  })

  const onClickFeedback = () => {
    setVisible(true)
  }
  const onCloseModal = () => {
    setVisible(false)
  }

  const onSendTest = (index: number) => {
    setInput(testList[index]);
  }
  const onClickSend = async () => {
    if (!inputValue || inputValue.trim() === '') {
      Taro.showToast({
        title: '请输入你的问题',
      })
      return;
    }
    messages.push({
      role: 'user',
      content: inputValue,
    })
    setMessages([...messages])
    setInput('');
    const res = await axios.post('/baidu/ernie4', { messages })
    if (res && res) {
      setMessages(res.data)
      Taro.nextTick(() => {
        Taro.createSelectorQuery().select(`msg${messages.length - 2}`).boundingClientRect((rect: any) => {
          Taro.pageScrollTo({ scrollTop: rect.top, duration: 0 })
        }).exec()
      })
    }
  }

  const onInputChange = (e) => {
    setInput(e.detail.value)
  }

  return (
    <View className='page relative min-h-screen pb-[170px] bg-[rgba(143,201,255,0.78)] flex flex-col' style={{ paddingTop: 94 }}>
      {/* <Text className='text'>AI先知</Text> */}
      <View ref={infoRef} className=" flex-1 relative">
        <View className='w-full bg-white p-3 flex flex-row items-center justify-between'>
          <View className='flex flex-row items-center justify-center'>
            <Image src={require('./images/logo.png')} className='w-[48px] h-[48px] mr-1' />
            <Text>
              健康助手（测试版）
            </Text>
          </View>
          <Image
            src={require('./images/more.png')}
            className='w-[48px] h-[48px]'
            onClick={onClickFeedback} />
        </View>
        <View className='w-full bg-white py-5 px-3 text-center font-bold'>
          健康助手（测试版）
        </View>
        <View className='px-2 mt-2 pb-[120px]'>
          <View className='bg-white px-3 py-3 rounded-lg overflow-hidden'>
            <View className='text-black font-extrabold text-[48px]'>Hi 这里有新的发现</View>
            <View className='text-black text-[30px] mt-3'>
            我是疫苗先知（测试版），能帮助你快速获取医典健康知识，助你更换了解健康~
            </View>
            <View className='mt-3'>
              {
                [1, 2, 3, 4].map((item, index) => {
                  return (
                    <View key={index} className='flex flex-row items-center justify-between mb-5'>
                      <View className='text-[28px] font-semibold text-black'>
                        {
                          testList[index]
                        }
                      </View>
                      <View className='w-[160px] h-[64px] rounded-[30px] overflow-hidden text-center bg-[#ebf7eb]'>
                        <Text className='text-[26px] text-[#0bcaf2] leading-[64px]' onClick={() => onSendTest(index)}>去试试</Text>
                      </View>
                    </View>
                  )
                })
              }
            </View>
            <View className='text-[#999] text-[24px] mt-3 leading-[38px]'>
              <View>
                当前回调范围内仅限于部分健康知识，如遇问题欢迎反馈（点击页面右上角的向我反馈）
              </View>
              <View>
                请注意！回答结果不能作为医疗诊断或者就医决策依据，如有不适，请尽快就医。
              </View>
            </View>
          </View>
          <View className='bg-transparent mt-3'>
            {
              messages.map((item, index) => {
                if (item.role === 'user') {
                  return (
                    <View
                      id={`msg${index}`}
                      key={index}
                      className={classNames('flex flex-row items-start mb-3', 'justify-end')}>
                        <View className='bg-white flex-1 text-right rounded-lg overflow-hidden py-4 px-3'>
                          <Text className=''>{item.content}</Text>
                        </View>
                      <Image
                        src={require('./images/user.png')}
                        className='w-[48px] h-[48px] ml-2' />
                    </View>
                  )
                }
                return (
                  <View
                    id={`msg${index}`}
                    key={index}
                    className={classNames('flex flex-row items-start mb-3', 'justify-start')}>
                    <Image src={require('./images/ai_avatar.png')}
                      className='w-[48px] h-[48px] mr-2' />
                    <View className='bg-white flex-1 text-left rounded-lg overflow-hidden py-4 px-3'>
                      <Text className=''>{item.content}</Text>
                    </View>
                  </View>
                )
              })
            }
          </View>
        </View>
      </View>
      <View className='fixed left-0 bottom-[160px] right-0 flex flex-row items-center h-[120px] bg-white px-3'>
        <Input
          value={inputValue}
          onInput={onInputChange}
          placeholder='请输入你的健康问题'
          className='flex-1 pl-2 h-[90px] rounded-lg overflow-hidden bg-[#FFF]'
          style={{ border: '1px solid #eee' }}
        />
        <Button className='ml-2 flex items-center justify-center bg-transparent' onClick={onClickSend}>
          <Image src={require('./images/send.png')} className='w-[48px] h-[48px]' />
        </Button>
      </View>
      {
        visible &&
        <FeedbackModal
          close={onCloseModal} />
      }
    </View>
  )
}

const FeedbackModal = (props: {
  close: () => void
}) => {
  const [fbValue, setFbInput] = useState('')
  const [uploadFile, setUploadFile] = useState('')
  const [uploadImgUrl, setUploadImgUrl] = useState('')
  const { close } = props
  const onClickClose = () => {
    close && close();
  }

  // 转base64
  const fileToBase64 = (filePath) => {
    return new Promise((resolve) => {
      let fileManager = Taro.getFileSystemManager();
      fileManager.readFile({
        filePath,
        encoding: 'base64',
        success: (e: any) => {
          resolve(`data:image/jpg;base64,${e.data}`);
        }
      });
    });
  };

  const onClickUpload = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: async (res) => {
        Taro.showLoading({
          title: '上传中...',
        })
        // let file: any = await fileToBase64(res.tempFilePaths[0])
        let file = res.tempFilePaths[0]
        if (file) {
          Taro.uploadFile({
            url: `${process.env.TARO_APP_HOST_API}/upload/upload`,
            filePath: res.tempFilePaths[0],
            name: 'pic',
            success: (uploadRes) => {
              setUploadFile(file);
              if (uploadRes && uploadRes.data) {
                const dataRes = JSON.parse(uploadRes.data)
                setUploadImgUrl(dataRes.data);
              }
            },
            fail: () => {
              Taro.showToast({
                title: '上传失败，请重试',
              })
            },
            complete: () => {
              Taro.hideLoading()
            }
          })
          // 更换图像
          // // @ts-ignore
          // 小程序没有formdata
          // const uploadRes = await axios.post('/upload/upload', formData, {
          //   headers: {
          //     'Content-Type': 'multipart/form-data'
          //   }
          // })
          // setUploadFile(file);
          // debugger;
          // if (uploadRes && uploadRes) {
          //   setUploadImg(uploadRes.data)
          // }
          // let uploadRes: any = await profileStore.uptdate_profile_avatar({ data: file })
          // if (uploadRes) {
          //   // TODO
          // }
        }
      }
    })
  }

  const onContentChange = (e: any) => {
    setFbInput(e.target.value)
  }

  const onClickSubmit = async () => {
    if (!fbValue || fbValue.trim() === '') {
      Taro.showToast({
        title: '请输入反馈内容',
        icon: 'none'
      });
      return;
    }
    const res = await axios.post('/subject/feeBack', {
      content: fbValue,
      imgUrl: uploadImgUrl
    })
    if (res && res) {
      Taro.showToast({
        title: '反馈成功',
        icon: "success"
      })
      close && close();
    }
  }

  return (
    <View className='absolute z-10 left-0 right-0 bottom-0 top-0 bg-[rgba(0,0,0,0.4)] flex flex-col justify-end'>
      <View className='w-full mb-[170px] px-3 py-4 bg-white relative'>
        <Image
          onClick={onClickClose}
          src={require('./images/close.png')}
          className='absolute top-2 right-2 w-[36px] h-[36px]' />
        <View className='flex flex-row items-center'>
          <Text className='text-[#333] text-[30px]'>
            请输入产品功能问题及反馈意见
          </Text>
          <Text className='text-[red] ml-1'>*</Text>
        </View>
        <Textarea
          className='h-[300px] border w-full bg-white rounded-lg overflow-hidden'
          maxlength={500}
          style={{
            border: '1px solid #eee'
          }}
          value={fbValue}
          onInput={e => onContentChange(e)}
          showCount
        />
        <View className='text-[28px] font-semibold mt-8'>
          相关截图
        </View>
        <View className='flex flex-row items-center'>
          <View onClick={onClickUpload} className='w-[200px] h-[200px] text-center leading-[200px] bg-[#999] text-[#fff]'>
            {
              uploadFile ?
                <Image src={uploadFile} className='w-full h-full' />
                :
                '+上传图片'
            }
          </View>
          <View className='ml-2'>
            <View>支持上传图片</View>
            <View>格式为JPG或者PNG，大小在5M以内</View>
          </View>
        </View>
        <View className='flex flex-row items-center justify-center mt-10'>
          <View
            onClick={onClickSubmit}
            className='w-[400px] h-[80px] rounded-[40px] overflow-hidden bg-[#0bcaf2] text-center leading-[80px] text-[#fff]'>提交反馈</View>
        </View>
      </View>
    </View >
  )
}
